﻿using MesBSW.BLL.Mes;
using MesBSW.Tools;
using MesBSW.View.Dialog.Role;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace MesBSW.View.Mes
{
    /// <summary>
    /// 异常工单界面
    /// </summary>
    public partial class AbnormalOrderFrm : UIPage
    {
        #region 调用内部BLL层
        AbnormalOrderBLL abnormalOrderBLL = new AbnormalOrderBLL();

        private SqlSugarClient Db = SqlSugares.GetInstance();
        #endregion

        public AbnormalOrderFrm()
        {
            InitializeComponent();
            DateTime firstDayOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            DateTime thirtyDaysAgo = firstDayOfMonth.AddDays(-30);
            this.PlayDate.Text = thirtyDaysAgo.ToString("yyyy-MM-dd");


            this.EndDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
        }

        /// <summary>
        /// 查询异常工单数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            //var list = abnormalOrderBLL.SelectAbnormalOrder(this.txtProdNumber.Text.ToString(), this.PlayDate.Text.ToString(), this.EndDate.Text.ToString());
            //DataTable dt = list.ToDataTable();
            //dt.Columns.Add("seq", typeof(int));
            //// 为每一行的序号列赋值
            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    dt.Rows[i]["seq"] = i + 1;
            //}
            //this.dgvRepair.DataSource = dt;
            //ViewData();
            select(); 
        }
        /// <summary>
        /// 解除异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void btnClear_Click(object sender, EventArgs e)
        {
            //获取选中的数据
            try
            {
                int selectIndex = uiDataGridView1.SelectedIndex;
                string ProdNumber = uiDataGridView1.Rows[selectIndex].Cells["prod_number1"].Value.ToString();//工单号
                int id = uiDataGridView1.Rows[selectIndex].Cells["id"].Value.ObjToInt();//明细ID
                DateTime end_time = uiDataGridView1.Rows[selectIndex].Cells["end_time"].Value.ObjToDate();//异常时间
                var Choose = uiDataGridView1.Rows[selectIndex].Cells["isChoose"].Value.ObjToBool();
                if (Choose == true)
                {
                    if (end_time.ToString() != "0001/1/1 0:00:00")//等于这个默认值就是空
                    {
                        UIMessageBox.ShowInfo("当前异常已处理，无需解除！");
                        return;
                    }
                    //线二的严重异常只能由组长解除
                    if (uiDataGridView1.Rows[selectIndex].Cells["status_name"].Value.ToString() == "严重异常" && ProdNumber.Contains("GL02"))
                    {
                        var list = Db.Context.SqlQueryable<object>($@"select
	                        base_role_id
                        from
	                        base_user_role
                        where
	                        base_user_id = {MainFrm.LoginUser.id}").ToList();
                        dynamic dylist = list;
                        if (dylist[0].base_role_id != 26)
                        {
                            list = Db.Context.SqlQueryable<object>($@"SELECT STRING_AGG(T1.real_name, '、') AS concatenated_real_names
                            FROM base_user T1 
                            LEFT JOIN base_user_role T2 ON T1.id = T2.base_user_id
                            LEFT JOIN base_role T3 ON T3.id = T2.base_role_id
                            WHERE T3.id = 26;").ToList();
                            if(list.Count > 0)
                            {
                                dylist = list;
                                UIMessageBox.ShowInfo("不是品质，没有权限解除！请找组长"+ dylist[0].concatenated_real_names);
                                return;
                            }
                            UIMessageBox.ShowInfo("不是品质，没有权限解除！");
                            return;
                        }
                    }
                    abnormalOrderBLL.UpdateAbnormalOrder(ProdNumber, id);
                    //刷新明细
                    select();
                    UIMessageBox.ShowSuccess("已经解除异常状态！");
                }
                else
                {
                    UIMessageBox.ShowError("请选择一张工单 ！");
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError("请选择一张工单 ！");
            }
        }
        /// <summary>
        /// 设置工单状态为普通异常或严重异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOutput_Click(object sender, EventArgs e)
        {
            if (this.txtProdNumber.Text == "")
            {
                UIMessageBox.ShowError("请在工单号输入工单！");
                return;
            }
            var ProdNumberList = abnormalOrderBLL.SelectAbnormalOrder(this.txtProdNumber.Text.ToString(), this.PlayDate.Text.ToString(), this.EndDate.Text.ToString());
            if (ProdNumberList.Count == 0)
            {
                UIMessageBox.ShowError("工单不存在");
                return;
            }
            dynamic dylist = ProdNumberList;
            int curr_site_id = dylist[0].curr_site_id;//站点ID
            string site_name = dylist[0].site_name;//站点名称
            string status_value = dylist[0].status_value;//完工状态
            if (status_value == "已完成")
            {
                UIMessageBox.ShowError("已完工，不可设置异常状态！");
                return;
            }
            AbnormalOrderDia addDeptDia = new AbnormalOrderDia(this.txtProdNumber.Text, curr_site_id, site_name);
            addDeptDia.ShowDialog();
            //刷新明细 
            select();
        }
        /// <summary>
        /// 单击主表显示明细表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvRepair_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int selectIndex = dgvRepair.SelectedIndex;
            string ProdNumber = dgvRepair.Rows[selectIndex].Cells["prod_number"].Value.ToString();//工单号
            var list = abnormalOrderBLL.SelectOrderAbnormal_Detail(ProdNumber);
            System.Data.DataTable dt = list.ToDataTable();
            this.uiDataGridView1.DataSource = dt;
            DateTableDetailColor(dt);
        }
        /// <summary>
        /// 明细颜色修改
        /// 未处理的异常标红
        /// </summary>
        private void DateTableDetailColor(System.Data.DataTable dt)
        {
            foreach (DataRow row in dt.Rows)
            {
                //严重异常且未处理
                if (row.ItemArray[4].ToString() == "严重异常" && row.ItemArray[9].ToString() == "")
                {
                    this.uiDataGridView1.Rows[row.Table.Rows.IndexOf(row)].DefaultCellStyle.ForeColor = Color.Red;
                }
                if (row.ItemArray[4].ToString() == "普通异常" && row.ItemArray[9].ToString() == "")
                {
                    this.uiDataGridView1.Rows[row.Table.Rows.IndexOf(row)].DefaultCellStyle.ForeColor = Color.Blue;
                }
            }
        }
        /// <summary>
        /// 扇形图
        /// </summary>
        private void ViewData()
        {
            //int selectIndex = uiDataGridView1.SelectedIndex;
            //string ProdNumber = uiDataGridView1.Rows[selectIndex].Cells["prod_number1"].Value.ToString();//工单号
            //Bitmap bmp = new Bitmap(guna2CirclePictureBox1.Width, guna2CirclePictureBox1.Height);
            //Graphics g = Graphics.FromImage(bmp);
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            //var list = abnormalOrderBLL.SelectViewData(this.txtProdNumber.Text.ToString(), this.PlayDate.Text.ToString(), this.EndDate.Text.ToString());//获取异常数据
            //dynamic dylist = list;
            //float startAngle = 0;
            //float endNumber = 0;
            //for (int i = 0; i < list.Count; i++)
            //{
            //    decimal Value = dylist[i].percentage;
            //    float f = (float)Value;
            //    if (i != 6)
            //    {
            //        endNumber += f;
            //    }
            //    switch (i)
            //    {
            //        case 0:
            //            SolidBrush solid = new SolidBrush(Color.DarkRed);
            //            g.FillPie(solid, 0, 0, bmp.Width, bmp.Height, startAngle, f * 360 / 100);
            //            uiLabel4.Text = dylist[i].reason_name + Value + "%";
            //            guna2PictureBox1.FillColor = Color.DarkRed;
            //            break;
            //        case 1:
            //            SolidBrush solid1 = new SolidBrush(Color.Red);
            //            g.FillPie(solid1, 0, 0, bmp.Width, bmp.Height, startAngle, f * 360 / 100);
            //            uiLabel5.Text = dylist[i].reason_name + Value + "%";
            //            guna2PictureBox2.FillColor = Color.Red;
            //            break;
            //        case 2:
            //            SolidBrush solid2 = new SolidBrush(Color.Yellow);
            //            g.FillPie(solid2, 0, 0, bmp.Width, bmp.Height, startAngle, f * 360 / 100);
            //            uiLabel6.Text = dylist[i].reason_name + Value + "%";
            //            guna2PictureBox3.FillColor = Color.Yellow;
            //            break;
            //        case 3:
            //            SolidBrush solid3 = new SolidBrush(Color.Blue);
            //            g.FillPie(solid3, 0, 0, bmp.Width, bmp.Height, startAngle, f * 360 / 100);
            //            uiLabel7.Text = dylist[i].reason_name + Value + "%";
            //            guna2PictureBox4.FillColor = Color.Blue;
            //            break;
            //        case 4:
            //            SolidBrush solid4 = new SolidBrush(Color.Green);
            //            g.FillPie(solid4, 0, 0, bmp.Width, bmp.Height, startAngle, f * 360 / 100);
            //            uiLabel8.Text = dylist[i].reason_name + Value + "%";
            //            guna2PictureBox5.FillColor = Color.Green;
            //            break;
            //        case 5:
            //            SolidBrush solid5 = new SolidBrush(Color.Black);
            //            g.FillPie(solid5, 0, 0, bmp.Width, bmp.Height, startAngle, f * 360 / 100);
            //            uiLabel9.Text = dylist[i].reason_name + Value + "%";
            //            guna2PictureBox6.FillColor = Color.Black;
            //            break;
            //        case 6:
            //            SolidBrush solid6 = new SolidBrush(Color.Beige);
            //            g.FillPie(solid6, 0, 0, bmp.Width, bmp.Height, startAngle, (100 - endNumber) * 360 / 100);
            //            uiLabel10.Text = dylist[i].reason_name + Value + "%";
            //            guna2PictureBox8.FillColor = Color.Beige;
            //            break;
            //    }
            //    startAngle += f * 360 / 100;
            //}
            //guna2CirclePictureBox1.Image = bmp;
            //string AvgTime = abnormalOrderBLL.AvgTime(this.PlayDate.Text.ToString(), this.EndDate.Text.ToString());//获取平均处理时间
            //uiLabel11.Text = "平均处理时间：" + AvgTime;
        }
        /// <summary>
        /// 查询工单异常
        /// </summary>
        /// <returns></returns>
        public void select()
        {
            var list = abnormalOrderBLL.SelectOrderAbnormal_Detail(this.txtProdNumber.Text.ToString(), this.PlayDate.Text.ToString(), this.EndDate.Text.ToString());
            System.Data.DataTable dt = list.ToDataTable();
            this.uiDataGridView1.DataSource = dt;
            //if (dt.Columns.Contains("seq"))
            //{
            //    dt.Columns.Remove("seq");
            //}
            //dt.Columns.Add("seq", typeof(int));
            //// 为每一行的序号列赋值
            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    dt.Rows[i]["seq"] = i + 1;
            //}
            this.dgvRepair.DataSource = dt;
            DateTableDetailColor(dt);
        }
        private void uiLabel6_Click(object sender, EventArgs e)
        {

        }

        private void uiDataGridView1_Sorted(object sender, EventArgs e)
        {
            // 获取DataGridView当前显示的数据
            System.Data.DataTable dt = new System.Data.DataTable();
            foreach (DataGridViewColumn col in uiDataGridView1.Columns)
            {
                dt.Columns.Add(col.HeaderText);
            }

            foreach (DataGridViewRow row in uiDataGridView1.Rows)
            {
                DataRow dRow = dt.NewRow();
                foreach (DataGridViewCell cell in row.Cells)
                {
                    dRow[cell.ColumnIndex] = cell.Value;
                }
                dt.Rows.Add(dRow);
            }

            foreach (DataRow row in dt.Rows)
            {
                //严重异常且未处理
                if (row.ItemArray[10].ToString() == "" && row.ItemArray[5].ToString() == "严重异常")
                {
                    this.uiDataGridView1.Rows[row.Table.Rows.IndexOf(row)].DefaultCellStyle.ForeColor = Color.Red;
                }
                if (row.ItemArray[10].ToString() == "" && row.ItemArray[5].ToString() == "普通异常")
                {
                    this.uiDataGridView1.Rows[row.Table.Rows.IndexOf(row)].DefaultCellStyle.ForeColor = Color.Blue;
                }
            }
        }
        /// <summary>
        /// 导出品质检验数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiHeaderButton1_Click(object sender, EventArgs e)
        {
            var list = abnormalOrderBLL.SelectOrderAbnormal_Detail(this.txtProdNumber.Text.ToString(), this.PlayDate.Text.ToString(), this.EndDate.Text.ToString());
            System.Data.DataTable dt = list.ToDataTable();
            if(dt.Rows.Count == 0)
            {
                UIMessageBox.ShowWarning("没有可导出的数据！");
                return;
            }
            DateTime tmpDay = DateTime.Now;
            string fileName = "异常工单" + tmpDay.ToString("yyyyMMdd") + "_" + tmpDay.ToString("HHmmss") + ".xlsx";
            string basePath = System.Windows.Forms.Application.StartupPath + "\\排单计划";
            var workbook = new XSSFWorkbook();
            // 创建工作表对象
            var sheet = workbook.CreateSheet("异常工单");
            List<string> TopName = new List<string>(new string[] { "工单号", "异常名称", "异常状态", "异常数量", "站点", "操作人"
                , "异常时间", "处理时间", "备注" });
            List<string> TopNameEng = new List<string>(new string[] { "prod_number1", "site_name", "status_name", "abnormal_qty", "reason_name", "real_name"
                , "begin_time", "end_time", "remark" });
            for (int i = 0; i < 9; i++)
            {
                sheet.SetColumnWidth(i, 12 * 512);
            }

            //标题字体样式
            var titleStyle = workbook.CreateCellStyle();
            NPOI.SS.UserModel.IFont titleFont = workbook.CreateFont();
            titleFont.IsBold = true;
            titleFont.FontHeightInPoints = 18;
            titleStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            titleStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            titleStyle.WrapText = true;
            titleStyle.SetFont(titleFont);

            // 内容字体样式
            var titleStyle1 = workbook.CreateCellStyle();
            NPOI.SS.UserModel.IFont titleFont1 = workbook.CreateFont();
            titleFont1.IsBold = true;
            titleFont1.FontHeightInPoints = 12;
            titleStyle1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            titleStyle1.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            titleStyle1.SetFont(titleFont1);


            for (int i = 0; i < dt.Rows.Count + 1; i++)
            {
                IRow row = sheet.CreateRow(i);
                //标题栏数据
                if (i == 0)
                {
                    for (int j = 0; j < TopName.Count; j++)
                    {
                        row.CreateCell(j).SetCellValue(TopName[j]);
                        sheet.GetRow(i).GetCell(j).CellStyle = titleStyle;
                    }
                }
                //内容数据
                if (i > 0)
                {
                    for (int j = 0; j < TopName.Count; j++)
                    {
                        row.CreateCell(j).SetCellValue(dt.Rows[i - 1][TopNameEng[j]].ToString());
                        sheet.GetRow(i).GetCell(j).CellStyle = titleStyle1;
                    }
                }
            }


            //导出
            using (var fileStream = new FileStream(basePath + "\\" + fileName, FileMode.Create))
            {
                workbook.Write(fileStream);
            }
            Process.Start(basePath);
        }
    }
}
